package com.sensei.search.client;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

public class SenseiConnResource {
	private final InetSocketAddress _addr;
	private SenseiClientHandler _client;
	private ChannelFactory _factory;
	private Channel _channel;
	
	public static class HostAddr{
		private String _hostname;
		private int _port;
		
		public HostAddr(String hostname,int port){
			_hostname = hostname;
			_port = port;
		}
		
		public String getHostname(){
			return _hostname;
		}
		
		public int getPort(){
			return _port;
		}
	}
	
	public SenseiConnResource(HostAddr addr){
		this(new InetSocketAddress(addr.getHostname(),addr.getPort()));
	}
	
	public SenseiConnResource(InetSocketAddress addr){
		_addr = addr;
		_factory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool());
		ClientBootstrap bootstrap = new ClientBootstrap(_factory);
		bootstrap.setPipelineFactory(new SenseiClientPipelineFactory());
		bootstrap.setOption("tcpNoDelay", true);
		bootstrap.setOption("keepAlive", true);
		
		ChannelFuture connectFuture = bootstrap.connect(_addr);
		_channel = connectFuture.awaitUninterruptibly().getChannel();
		_client = _channel.getPipeline().get(SenseiClientHandler.class);
	}
	
	public SenseiClientHandler getClientHandler(){
		return _client;
	}
	
	public void close(){
		try{
		  if (_channel!=null){
			_channel.close().awaitUninterruptibly();
		  }
		}
		finally{
		  if (_factory!=null){
			_factory.releaseExternalResources();
		  }
		}
	}
}
